/*
 * lectureVideo.cpp
 *
 *  Created on: 6 sept. 2010
 *      Author: Administrateur
 */

#include "lectureVideo.h"

#include <iostream>
#include <sstream>
//std::cout<<"nb "<<numberFrame<<std::endl;

	lectureVideo::lectureVideo(){
	}
	/*!
	 * Destructor
	 */
	lectureVideo::~lectureVideo(){

	}
	void lectureVideo::preparing(){
		currentFrame=0;
		stop=true;
	}
	void lectureVideo::initialize(QString filename){
		QByteArray encodedFileName = filename.toUtf8();
		char * charFName = encodedFileName.data();
		this->currentCapture = cvCaptureFromAVI(charFName);
		cvGrabFrame(this->currentCapture);
		cvSetCaptureProperty(this->currentCapture, CV_CAP_PROP_POS_AVI_RATIO, 1. );
		this->numberFrame = (int) cvGetCaptureProperty(this->currentCapture, CV_CAP_PROP_POS_FRAMES );
		cvSetCaptureProperty(this->currentCapture, CV_CAP_PROP_POS_FRAMES, 0. );
		currentFrame=1;
		previewImage=cvRetrieveFrame(currentCapture);
	}
	void lectureVideo::processing(){
			if (currentFrame!=numberFrame-1){
				cvGrabFrame(currentCapture);
				currentImage=cvRetrieveFrame(currentCapture);
				currentFrame++;
				std::cout<<"NB "<<currentFrame<<std::endl;
			} else {
				stop=false;
			}
	}

	QImage lectureVideo::getImage(){
		return IplToQImage(currentImage);
	}

	QImage lectureVideo::getPreviewImage(){
		return IplToQImage(previewImage);
	}

	bool lectureVideo::getStop(){
		return stop;
	}

	QImage lectureVideo::IplToQImage(const IplImage *newImage)
		{
			QImage qtemp;
			if(newImage && newImage->width>0)
			{
				int x;
				int y;
				char* data = newImage->imageData;
				qtemp= QImage(newImage->width, newImage->height,QImage::Format_RGB32 );

				for( y = 0; y < newImage->height; y++, data +=newImage->widthStep )
					for( x = 0; x < newImage->width; x++)
					{
						uint *p = (uint*)qtemp.scanLine(newImage->height-y-1) +x;
						*p = qRgb(data[x * newImage->nChannels+2],
								data[x * newImage->nChannels+1],
								data[x * newImage->nChannels]);
					}
			}
			return qtemp;
		}

